angular.module("module.orderCreate",[])
    .config(['$stateProvider',function ($stateProvider) {
        $stateProvider
            .state('home.orderCreate',{
                url:"/orderCreate",
                templateUrl:"orderCreate/orderCreate.html",
                controller:'OrderCreateController',
                controllerAs:'vm'
            })
    }])
    .controller('OrderCreateController',[function () {
        var vm=this;
//通过修改页面url路径，解决一开始进入数据加载出错问题
        var pathname = window.location.pathname;
        if(pathname =="/store"){
            window.location.pathname="/orderCreate";
        }

        var searchArray=window.location.search.slice(1).split("&");
        for (var i=0;i<searchArray.length;i++){
            searchArray[i]=searchArray[i].split("=");
            data[searchArray[i][0]]=searchArray[i][1];
        }
        if (data.orderNo){
            $("#create_order").html("加菜");
        }
        if (data.roomId){
            $("#roomId").val(data.roomId)
        }
        $.getJSON("printList",{shopId:shopId},function (res) {
            data.printList=res.data.dataList;
            $.getJSON("goodsTypeList",{shopId:shopId},function (res) {
                data.typeList=res.data.dataList;
                $('#good_content').html(template("good_content_tmpl",data));

                //实现标签页功能
                $('.gn_tabs a').off().on("click",function(e) {
                    e.preventDefault();
                    //    这里调用了boostrap的tap(),实现了标签页的功能呢;
                    $(this).tab('show');
                    var tmpl = e.target.hash.replace('#','');
                    loadpage(tmpl);
                });

                $("#search_a").off().on("click",function (e) {
                    e.preventDefault();
                    var goodsPinyin=$("#searchStr").val();
                    console.log("goodsPinyin",goodsPinyin);
                    //    这里调用了boostrap的tap(),实现了标签页的功能呢;
                    $(this).tab('show');
                    var tmpl = e.target.hash.replace('#','');
                    $("#"+tmpl).data("goodsPinyin",goodsPinyin);
                    $("#"+tmpl).attr('page',1);
                    loadpage(tmpl);
                });

                /*  根据选择的标签页及标签页对应的页面元素上的page属性对页面数据赋值
                 给各个不同列表中的按钮附上click调用函数，给分页的页码附上click调用函数*/
                function loadpage(tmpl){
                    //    根据传入的标签页得到活动的列表；接着取得列表模块的page属性；
                    if (!tmpl) tmpl = 'goods';
//            console.log(tmpl);
                    var tmplObj = $('#'+tmpl);
                    var url = tmplObj.attr('url') || '';
                    var page = tmplObj.attr('page') || 1;
                    var goodsTypeId=tmplObj.data("goods-type-id");
                    var goodsPinyin=tmplObj.data("goodsPinyin");
//            console.log(tmplObj);
                    url += '?pi=' + page;
                    url+='&shopId='+shopId;
//            console.log("goodsTypeId",goodsTypeId);
                    if (goodsTypeId)url += '&goodsTypeId=' + goodsTypeId;
//            console.log("goodsPinyin",goodsPinyin);
                    if (goodsPinyin)url += '&goodsPinyin=' + goodsPinyin;
                    console.log(url);
                    //  根据选择的标签页及标签页对应的页面元素上的page属性对页面数据赋值
                    $.getJSON(url, function(res){
//                    console.log("goods_res",res);
                        if (!res.succeed) return toast('获取数据失败，失败原因：'+res.message);
                        //               填充页面模板
//                    console.log(res.data);
                        tmplObj.html(template('goods_tmpl', res.data));

                        // 给各个不同列表中的按钮附上click调用函数，给分页的页码附上click调用函数

                        //              给页码部分附上功能
                        topage(tmpl);
//——————实现加入订单功能—————————————————————————————————————————————————
                        $('[name=addGoods]').off().on("click",function () {
                            var count=1;
                            var goodId=$(this).data("goodId");
                            updata_right_sidebar({goodId:goodId,count:count},res)
                        });
//————————————————————————————————————————————————————————————————

//———————————提交订单按钮(数据来源是右侧栏中订单详情部分的html)———————————————————————————————————————————————
                        if (data.orderNo){
                            $("#create_order").off().on("click",function () {
                                var temporary_goodList=$("#right_sidebar_top").find("div");
                                console.log("temporary_goodList",temporary_goodList);
                                var goodList=[];
                                for (var i=0;i<temporary_goodList.length;i++){
                                    console.log("temporary_goodList.eq(i)",temporary_goodList.eq(i)[0]);
                                    var goodsId=temporary_goodList.eq(i).data().goodsId;
                                    if(temporary_goodList.eq(i).data().units=='斤'){
                                        var goodsCount=temporary_goodList.eq(i).data().goodsCount*500;
                                    }else {
                                        var goodsCount=temporary_goodList.eq(i).data().goodsCount;
                                    }
                                    var goodsNote=temporary_goodList.eq(i).data().goodsNote;
                                    console.log("goodsNote",goodsNote);
                                    goodList.push({
                                        goodsId:goodsId,
                                        goodsCount:goodsCount,
                                        goodsNote:goodsNote
                                    })
                                }

                                console.log("goodList",goodList);
                                var isMember=$("#is_member").is(':checked');
                                para={
                                    orderNo:data.orderNo,
                                    roomId:$('#roomId').val() ? $('#roomId').val() : '',
                                    orderInfo:JSON.stringify(goodList),
                                    totalMoney:isMember?parseInt(parseFloat($("#member_total").html())*100):parseInt(parseFloat($("#common_total").html())*100)
                                };
                                console.log(para);
                                $.getJSON('addGoods', para, function(res){
                                    console.log("res",res);
                                    if (!res.succeed) {
                                        return alert(res.message);
                                    }
                                    toast('加菜成功,重新加载中...', 'success', function(){
                                        location.reload();
                                    });
                                });
                            })
                        }else {
                            $("#create_order").off().on("click",function () {
                                var temporary_goodList=$("#right_sidebar_top").find("div");
                                console.log("temporary_goodList",temporary_goodList);
                                var goodList=[];
                                for (var i=0;i<temporary_goodList.length;i++){
                                    console.log("temporary_goodList.eq(i)",temporary_goodList.eq(i)[0]);
                                    var goodsId=temporary_goodList.eq(i).data().goodsId;
                                    var goodsCount;
                                    if(temporary_goodList.eq(i).data().units=='斤'){
                                        goodsCount=temporary_goodList.eq(i).data().goodsCount*500;
                                    }else {
                                        goodsCount=temporary_goodList.eq(i).data().goodsCount;
                                    }
                                    var goodsNote=temporary_goodList.eq(i).data().goodsNote;
                                    console.log("goodsNote",goodsNote);
                                    goodList.push({
                                        goodsId:goodsId,
                                        goodsCount:goodsCount,
                                        goodsNote:goodsNote
                                    })
                                }

                                console.log("goodList",goodList);
                                var isMember=$("#is_member").is(':checked');

                                para={
                                    orderNo:'',
                                    appId:data.appId,
                                    openId:'0',
                                    subOpenId:'0',
                                    shopId:shopId,
                                    nonceStr:'',
                                    timestamp:Date.parse(new Date()),
                                    orderInfo:JSON.stringify(goodList),
                                    orderAttachInfo:JSON.stringify({
                                        'totalMoney':isMember?parseInt(parseFloat($("#member_total").html())*100):parseInt(parseFloat($("#common_total").html())*100),
                                        'roomId':$('#roomId').val() ? $('#roomId').val() : '',
                                        'message':$('#message').val() ? $('#message').val() : '',
                                        'payType':'10'
                                    })
                                };
                                console.log(para);
                                $.getJSON('/swpay/getJsapiCharge2', para, function(res){
                                    console.log("res",res);
                                    if (!res.succeed) {
                                        return alert(res.message);
                                    }
                                    toast('下单成功,重新加载中...', 'success', function(){
                                        location.reload();
                                    });
                                });
                            })
                        }
                    });
                }
//————————————————————————————————————————————————————————————————

                //给页码附上换页功能
                function topage(tmpl){
                    //    为所有的页码添加click事件
                    $('.tab-pane.active .pagination a').on('click', function(){
                        //      将被点击页码的href属性值赋给正在活动中的列表的page属性
                        $('.tab-pane.active').attr('page', $(this).attr('href'));
                        //      调用loadpage函数刷新页面数据
                        loadpage(tmpl);
                        return false;
                    });
                }
                //更新右侧栏的数据
                function updata_right_sidebar(param,res) {
                    var good_data= create_good_data(param,res);
                    update_order_detail_html(good_data);
                    update_order_total_html();


                    $(".good_count").off().on('change',function () {
                        var goodId=$(this).attr("id");
                        var count=$(this).val();
                        console.log("$(this)",$(this));
                        console.log("goodId",goodId);
                        console.log("count",count);
                        updata_right_sidebar({goodId:goodId,count:count},res);
                    });

                    $(".good_note").off().on('change',function () {
                        var goodsNote=$(this).val();
                        var goodId=$(this).data("goodId");
                        console.log("$(this)",$(this));
                        console.log("goodsNote",goodsNote);
                        console.log("goodId",goodId);
                        updata_right_sidebar({goodId:goodId,goodsNote:goodsNote},res);
                    });
//——————实现加减按钮————————————————————————————————————————————————————
                    //这里用off清除掉原先添加的click事件，保证一个元素上只有一个click事件，即保证了一次点击只触发一次click事件
                    $('span.glyphicon-plus').off().on("click",function () {
                        console.log("add clicked");
                        var goodId=$(this).attr("name");
//                console.log("add goodId",goodId);
//                console.log($("#right_sidebar_top #"+goodId).eq(0).html());
                        var count=parseInt($("#right_sidebar_top #"+goodId).eq(0).html())+1;
                        updata_right_sidebar({goodId:goodId,count:count},res);
                    });
                    //这里用off清除掉原先添加的click事件，保证一个元素上只有一个click事件，即保证了一次点击只触发一次click事件
                    $('span.glyphicon-minus').off().on("click",function () {
                        console.log("min clicked");
                        var goodId=$(this).attr("name");
//                console.log("min goodId",goodId);
//                console.log($("#right_sidebar_top #"+goodId).eq(0).html());
                        if (parseInt($("#right_sidebar_top #"+goodId).eq(0).html())>0){
                            var count=parseInt($("#right_sidebar_top #"+goodId).eq(0).html())-1;
                            updata_right_sidebar({goodId:goodId,count:count},res)
                        }
                    });
//————————————————————————————————————————————————————————————————
                }

//        从页面和缓存获取数据组装good_data对象
                function create_good_data(param,res) {
                    var good_data={};
                    good_data.good={};
                    console.log('param',param);
                    if ($('#order_good'+param.goodId).length>0){
                        if (param.count==0||param.count){
                            good_data.good.count=param.count
                        }else {
                            good_data.good.count=$('#order_good'+param.goodId).data().goodsCount;
                        }
                        good_data.good.goodsId=param.goodId||$('#order_good'+param.goodId).data().goodId;
                        good_data.good.goodsNote=param.goodsNote||$('#order_good'+param.goodId).data().goodsNote;
                        good_data.good.goodsMemberPrice=$('#order_good'+param.goodId).data().goodsMemberPrice;
                        good_data.good.goodsCommonPrice=$('#order_good'+param.goodId).data().goodsCommonPrice;
                        good_data.good.goodsLogo=$('#order_good'+param.goodId).data().goodsLogo;
                        good_data.good.goodsName=$('#order_good'+param.goodId).data().goodsName;
                        good_data.good.units=$('#order_good'+param.goodId).data().units;
                        var member_sum=good_data.good.count*good_data.good.goodsMemberPrice;
                        var common_sum=good_data.good.count*good_data.good.goodsCommonPrice;
                        good_data.good.member_sum=member_sum;
                        good_data.good.common_sum=common_sum;
                    }else {
                        for (var i=0;i<res.data.dataList.length;i++){
                            if (res.data.dataList[i].goodsId==param.goodId){
                                good_data.good=res.data.dataList[i];
                            }
                        }
                        good_data.good.count=param.count;
                        var member_sum=good_data.good.count*good_data.good.goodsMemberPrice;
                        var common_sum=good_data.good.count*good_data.good.goodsCommonPrice;
                        good_data.good.member_sum=member_sum;
                        good_data.good.common_sum=common_sum;
                    }
                    return good_data;
                }

//        操作订单详情部分html，根据商品数量修改右侧栏的订单
                function update_order_detail_html(good_data) {
                    console.log("good_data.good",good_data.good);
                    if ($('#order_good'+good_data.good.goodsId).length>0){
                        if (good_data.good.count==0){
                            $('#order_good'+good_data.good.goodsId).remove();
                        }else {
                            $('#order_good'+good_data.good.goodsId).replaceWith(template('right_sidebar_good',good_data))
                        }
                    }else {
                        $("#right_sidebar_top").append(template('right_sidebar_good',good_data))
                    }
                }

//        根据订单详情部分的html计算出订单总金额，修改总金额部分的html
                function update_order_total_html() {
                    var temporary_goodList=$("#right_sidebar_top").find("div");
                    var member_total=0,common_total=0;
                    for (var i=0;i<temporary_goodList.length;i++){
                        var data=temporary_goodList.eq(i).data();
                        member_total+=data.memberSum;
                        common_total+=data.commonSum;
                    }
                    $("#member_total").html((member_total/100).toFixed(2));
                    $("#common_total").html((common_total/100).toFixed(2));
                }
                loadpage();
            });
        });
    }]);